<?php

namespace App\Service\news;

use App\Jobs\NewsSendQueue;
use App\Models\news\NewsListModel;
use App\Models\news\NewsTemplateModel;
use App\Models\order\OrderModel;
use App\Models\system\ExceptionTableModel;
use App\Models\users\UsersModel;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class SendNoticeService
{

    protected int $newsId;

    public function __construct()
    {

    }


    /**
     * 获取接收人类型信息
     */
    private function getReceiveInfo($receive_type)
    {
        switch ($receive_type) {
            case 1:
                $user = UsersModel::where('is_cancel', 0)->get()->toArray();
                break;
            case 2:
                $user = UsersModel::where('is_cancel', 0)->get()->toArray();
                foreach ($user as $key => $value) {
                    $orderInfo = OrderModel::where('uid', $value['id'])->first();
                    if ($orderInfo) unset($user[$key]);
                }
                break;
            case 3:
                $user = UsersModel::rightJoin('order', 'order.uid', '=', 'users.id')->get()->toArray();
                break;
            default:
                $user = [];
        }

        return $user;
    }


    /**
     * 发送消息
     * @param $template_id
     * @return bool
     */
    public function send($template_id): bool
    {
        $newsInfo = NewsTemplateModel::find($template_id);
        if (!$newsInfo) {
            Log::error('消息推送异常: 无模版可推送');
            return false;
        }
        $userList = $this->getReceiveInfo($newsInfo->receive_type);
        if (!$userList) {
            Log::error('消息推送异常: 无用户可推送');
            return false;
        }
        try {
            DB::beginTransaction();

            foreach ($userList as $user) {
                $newsMiddleInfo = new NewsListModel();
                $newsMiddleInfo->news_id = $newsInfo->id;
                $newsMiddleInfo->uid = $user['id'];
                $newsMiddleInfo->create_time = time();
                $newsMiddleInfo->save();
            }

            $newsInfo->status = 1;
            $newsInfo->save();

            DB::commit();
            return true;
        } catch (\Exception $e) {
            DB::rollBack();
            ExceptionTableModel::insert([
                'type' => '发送消息异常',
                'message' => $e->getMessage() . $e->getLine()
            ]);
            return false;
        }

    }


    /**
     * 判断模版是否发送消息
     */
    public function isSend(): bool
    {
        $start = time() - 59;
        $end = time();
        $newsInfo = NewsTemplateModel::where('deleted_at', 0)
            ->where('send_type', 2)
            ->where('status', 0)
            ->whereBetween('send_time', [$start, $end])
            ->get()->toArray();

        if (!$newsInfo) {
            return false;
        }

        try {
            DB::beginTransaction();
            foreach ($newsInfo as $news) {
                NewsSendQueue::dispatch($news['id']);
            }
            DB::commit();
            return true;
        } catch (\Exception $e) {
            DB::rollBack();
            ExceptionTableModel::insert([
                'type' => '判断模版是否发送消息异常',
                'message' => $e->getMessage() . $e->getLine()
            ]);
            return false;
        }
    }


    /**
     * 删除消息模版
     */
    public function delete($id): bool
    {
        $res = NewsTemplateModel::where('id', $id)->update(['status' => 2]);
        if ($res) {
            return true;
        } else {
            return false;
        }
    }


}
